from PySide6.QtWidgets import QVBoxLayout, QHBoxLayout, QGridLayout, QDialog, QWidget, QMenu
from PySide6.QtCore import Qt
from PySide6.QtGui import QCursor
from .widgets.table_widget import CommonTableWidget
from .widgets.dialogs import BaseDialog, MessageOverlay
from .widgets.panels import BasePanel
from .widgets.basewidgets import *
from api import api
from common import config, utils

SUPPLIER_HEADER_COLUMNS = {
    "供货商名称": {"type": "text", "text": lambda x: x["name"]},
    "联系人": {"type": "text", "text": lambda x: x["contact"]},
    "联系电话": {"type": "text", "text": lambda x: x["phone"]},
    "微信": {"type": "text", "text": lambda x: x["wechat"] or ""},
    "地址": {"type": "text", "text": lambda x: x["address"]},
    "操作": {"type": "action"}
}

QUOTE_HEADER_COLUMNS = {
    "商品名称": {"type": "text", "text": lambda x: x["product"]["name"]},
    "商品单位": {"type": "text", "text": lambda x: x["product"]["unit"]},
    "商品售价": {"type": "text", "text": lambda x: x['product']['price']},
    "供应商报价": {"type": "text", "text": lambda x: x['cost_price']},
    "操作": {"type": "action"}
}

class SupplierPage(BasePanel):
    def __init__(self):
        super().__init__("供货商管理")
        self.setup_ui()
        self.setup_context_menu()
        
    def setup_ui(self):
        # 搜索和操作区域
        search_widget = SearchPanel()
        search_layout = QHBoxLayout(search_widget)
        
        # 搜索框
        self.search_input = SearchLineEdit()
        self.search_input.setPlaceholderText("根据供货商名称或者手机号搜索")
        self.search_input.textChanged.connect(self.flush_table)
        
        # 添加供货商按钮
        add_btn = BluePushButton("添加供货商")
        add_btn.clicked.connect(self.show_add_supplier_dialog)
        
        search_layout.addWidget(self.search_input)
        search_layout.addStretch()
        search_layout.addWidget(add_btn)
        
        self.main_layout.addWidget(search_widget)
        
        # 供货商表格
        table_widget = QWidget()
        table_widget.setObjectName("supplierTable")
        table_layout = QVBoxLayout(table_widget)
        
        self.supplier_table = CommonTableWidget(headers=SUPPLIER_HEADER_COLUMNS)
        self.supplier_table.pageSizeChanged.connect(self.flush_table)
        
        table_layout.addWidget(self.supplier_table)
        self.main_layout.addWidget(table_widget)

    def setup_context_menu(self):
        super().setup_context_menu()
        self.supplier_table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.supplier_table.customContextMenuRequested.connect(self.show_context_menu)

    def add_extra_context_menus(self, menu, pos):
        menu.addSeparator()
        add_supplier_action = menu.addAction("添加供应商")
        add_supplier_action.triggered.connect(self.show_add_supplier_dialog)
        
        # 如果是在表格中点击
        sender = self.sender()
        if sender == self.supplier_table and self.supplier_table.itemAt(pos):
            row = self.supplier_table.itemAt(pos).row()
            supplier_data = self.supplier_table.get_row_data(row)
            
            menu.addSeparator()
            
            # 供应商操作子菜单
            operations_menu = menu.addMenu("供应商操作")
            operations_menu.addAction("报价").triggered.connect(
                lambda: self.show_quote_dialog(row))
            operations_menu.addAction("编辑").triggered.connect(
                lambda: self.edit_supplier(row))
            delete_action = operations_menu.addAction("删除")
            delete_action.triggered.connect(lambda: self.delete_supplier(row))
            
            menu.addSeparator()
            
            # 供应商信息子菜单
            info_menu = menu.addMenu("供应商信息")
            info_menu.addAction(f"供应商名称: {supplier_data['name']}")
            info_menu.addAction(f"联系人: {supplier_data['contact']}")
            info_menu.addAction(f"联系电话: {supplier_data['phone']}")
            if supplier_data.get('wechat'):
                info_menu.addAction(f"微信: {supplier_data['wechat']}")
            info_menu.addAction(f"地址: {supplier_data['address']}")
    
    def load_data(self):
        """初始加载数据"""
        self.flush_table()
    
    def flush_table(self):
        """刷新表格数据"""
        suppliers = api.get_suppliers(
            search=self.search_input.text(),
            page=self.supplier_table.current_page,
            per_page=self.supplier_table.page_size
        )
        if not suppliers:
            return
            
        self.supplier_table.set_total_items(suppliers["count"])
        self.supplier_table.setRowCount(len(suppliers["items"]))
        for i, supplier in enumerate(suppliers["items"]):
            self.supplier_table.set_row_data(i, supplier)
            action_buttons = [
                {"text": "报价", "callback": self.show_quote_dialog},
                {"text": "编辑", "callback": self.edit_supplier},
                {"text": "删除", "callback": self.delete_supplier, "objectName": "deleteButton"}
            ]
            self.supplier_table.add_action_buttons(i, action_buttons)
    
    def edit_supplier(self, row):
        """编辑供货商"""
        supplier_data = self.supplier_table.get_row_data(row)
        dialog = SupplierDialog(self, supplier_data["id"])
        if dialog.exec() == QDialog.Accepted:
            # 更新供货商信息
            supplier = dialog.supplier_data
            supplier.pop("created_at")
            supplier_id = supplier.pop("id")
            api.update_supplier(supplier_id, **supplier)
            MessageOverlay.info(self, "供货商信息更新成功")
            self.flush_table()
    
    def delete_supplier(self, row):
        """删除供货商"""
        supplier_data = self.supplier_table.get_row_data(row)
        if MessageOverlay.question(self, f"确定要删除供货商 {supplier_data['name']} 吗？删除后将不能恢复。") == MessageOverlay.ACCEPTED:
            api.delete_supplier(supplier_data["id"])
            MessageOverlay.info(self, "供货商删除成功")
            self.flush_table()
    
    def show_add_supplier_dialog(self):
        """显示添加供货商对话框"""
        dialog = SupplierDialog(self)
        if dialog.exec() == QDialog.Accepted:
            # 添加新供货商
            api.add_supplier(**dialog.supplier_data)
            MessageOverlay.info(self, "供货商添加成功")
            self.flush_table()

    def show_quote_dialog(self, row):
        """显示报价对话框"""
        supplier_data = self.supplier_table.get_row_data(row)
        dialog = QuoteDialog(self, supplier_data["id"])
        dialog.exec()

class SupplierDialog(BaseDialog):
    def __init__(self, parent=None, supplier_id=None):
        super().__init__(parent)
        self.supplier_data = api.get_supplier(supplier_id) if supplier_id else {}
        self.setup_ui()
        
        # 如果是编辑模式，填充现有数据
        if self.supplier_data:
            self.name_input.setText(self.supplier_data["name"])
            self.contact_input.setText(self.supplier_data["contact"])
            self.phone_input.setText(self.supplier_data["phone"])
            self.wechat_input.setText(self.supplier_data["wechat"] or "")
            self.address_input.setText(self.supplier_data["address"])
    
    def setup_ui(self):
        self.setWindowTitle("编辑供货商" if self.supplier_data else "添加供货商")
        self.setMinimumWidth(500)
        
        layout = QVBoxLayout(self)
        
        # 表单布局
        form_layout = QGridLayout()
        
        # 供货商名称
        self.name_input = NormalLineEdit()
        form_layout.addWidget(NormalLabel("供货商名称:"), 0, 0)
        form_layout.addWidget(self.name_input, 0, 1)
        
        # 联系人
        self.contact_input = NormalLineEdit()
        form_layout.addWidget(NormalLabel("联系人:"), 0, 2)
        form_layout.addWidget(self.contact_input, 0, 3)
        
        # 联系电话
        self.phone_input = NormalLineEdit()
        form_layout.addWidget(NormalLabel("联系电话:"), 1, 0)
        form_layout.addWidget(self.phone_input, 1, 1)
        
        # 微信
        self.wechat_input = NormalLineEdit()
        form_layout.addWidget(NormalLabel("微信:"), 1, 2)
        form_layout.addWidget(self.wechat_input, 1, 3)
        
        # 地址
        self.address_input = NormalLineEdit()
        form_layout.addWidget(NormalLabel("地址:"), 2, 0)
        form_layout.addWidget(self.address_input, 2, 1, 1, 4)
        
        layout.addLayout(form_layout)
        
        # 使用BaseDialog的按钮布局
        button_layout = self.create_button_layout(self.validate_and_accept)
        layout.addLayout(button_layout)
    
    def validate_and_accept(self):
        """验证表单数据"""
        if not self.name_input.text():
            MessageOverlay.warning(self, "请输入供货商名称")
            self.name_input.setFocus()
            return
        
        if not self.contact_input.text():
            MessageOverlay.warning(self, "请输入联系人")
            self.contact_input.setFocus()
            return
        
        if not self.phone_input.text():
            MessageOverlay.warning(self, "请输入联系电话")
            self.phone_input.setFocus()
            return
        
        if not utils.match_phone_number(self.phone_input.text()):
            MessageOverlay.warning(self, "请输入正确的联系电话")
            self.phone_input.setFocus()
            return
        
        if not self.address_input.text():
            MessageOverlay.warning(self, "请输入地址")
            self.address_input.setFocus()
            return
        
        self.supplier_data.update({
            "name": self.name_input.text(),
            "contact": self.contact_input.text(),
            "phone": self.phone_input.text(),
            "wechat": self.wechat_input.text(),
            "address": self.address_input.text()
        })
        self.accept()

class QuoteDialog(BaseDialog):
    def __init__(self, parent=None, supplier_id=None):
        super().__init__(parent)
        self.supplier_id = supplier_id
        self.supplier_data = api.get_supplier(supplier_id) if supplier_id else None
        self.quotes = api.get_supplier_products(self.supplier_id)
        self.setup_ui()
        self.quotes_changed = False
        self.load_quote_data()
    
    def setup_ui(self):
        self.setWindowTitle(f"供应商报价 - {self.supplier_data['name']}")
        self.setFixedSize(800, 600)
        
        layout = QVBoxLayout(self)
        # 报价表格
        self.quote_table = CommonTableWidget(headers=QUOTE_HEADER_COLUMNS, pagination_position="none")
        layout.addWidget(self.quote_table)

        # 提醒
        self.warning_label = WarningLabel("⚠️当前报价清单有变动，请注意保存。")
        self.warning_label.setAlignment(Qt.AlignmentFlag.AlignRight)
        self.warning_label.setVisible(False)
        layout.addWidget(self.warning_label)
        
        # 底部按钮
        button_layout = QHBoxLayout()
        
        # 添加商品按钮
        add_product_btn = BluePushButton("添加商品")
        add_product_btn.clicked.connect(self.show_add_product_dialog)
        button_layout.addWidget(add_product_btn)
        
        button_layout.addStretch()

        # 取消按钮
        cancel_btn = WhitePushButton("取消")
        cancel_btn.clicked.connect(self.reject)
        button_layout.addWidget(cancel_btn)
        
        # 保存按钮
        save_btn = BluePushButton("保存")
        save_btn.clicked.connect(self.save_changes)
        button_layout.addWidget(save_btn)
        
        layout.addLayout(button_layout)

    def load_quote_data(self):
        """加载供应商报价数据"""
        self.quote_table.setRowCount(len(self.quotes))
        for i, quote in enumerate(self.quotes):
            self.quote_table.set_row_data(i, quote)
            action_buttons = [
                {"text": "删除", "callback": self.delete_quote, "objectName": "deleteButton"}
            ]
            self.quote_table.add_action_buttons(i, action_buttons)
        self.warning_label.setVisible(self.quotes_changed)

    def filter_table(self):
        """根据搜索文本过滤表格"""
        search_text = self.search_input.text().lower()
        for row in range(self.quote_table.rowCount()):
            item_data = self.quote_table.get_row_data(row)
            product_name = item_data["product"]["name"].lower()
            self.quote_table.setRowHidden(row, search_text not in product_name)

    def show_add_product_dialog(self):
        """显示添加商品对话框"""
        dialog = AddProductQuoteDialog(self, self.supplier_id)
        if dialog.exec() == QDialog.Accepted:
            self.quotes_changed = True
            self.quotes.append(dialog.submit_quote)
            self.load_quote_data()

    def delete_quote(self, row):
        """删除报价"""
        quote_data = self.quote_table.get_row_data(row)
        if MessageOverlay.question(self, f"确定要删除商品 {quote_data['product']['name']} 的报价吗？") == MessageOverlay.ACCEPTED:
            self.quotes_changed = True
            del self.quotes[row]
            self.load_quote_data()

    def save_changes(self):
        """保存修改的报价"""
        updated_quotes = []
        for row in range(self.quote_table.rowCount()):
            quote_data = self.quote_table.get_row_data(row)
            updated_quotes.append({
                "id": quote_data["product"]["id"],
                "cost_price": quote_data["cost_price"]
            })
        
        api.update_supplier_products(self.supplier_id, updated_quotes)
        MessageOverlay.info(self, "报价更新成功")
        self.accept()

class AddProductQuoteDialog(BaseDialog):
    def __init__(self, parent=None, supplier_id=None):
        super().__init__(parent)
        self.supplier_id = supplier_id
        self.setup_ui()
    
    def setup_ui(self):
        self.setWindowTitle("添加商品报价")
        self.setMinimumWidth(400)
        
        layout = QVBoxLayout(self)
        
        form_layout = QGridLayout()
        
        # 商品选择
        self.product_input = AutoCompleteLineEdit(
            self.query_products,
            "输入商品名称搜索",
            item_key="name"
        )
        form_layout.addWidget(NormalLabel("商品:"), 0, 0)
        form_layout.addWidget(self.product_input, 0, 1)
        self.product_input.selectedChanged.connect(self.update_current_price)
        
        # 报价输入
        self.price_input = NormalFloatSpinBox()
        form_layout.addWidget(NormalLabel("报价:"), 1, 0)
        form_layout.addWidget(self.price_input, 1, 1)

        # 当前售价
        self.current_price_label = NormalLabel("0")
        form_layout.addWidget(NormalLabel("售价:"), 2, 0)
        form_layout.addWidget(self.current_price_label, 2, 1)
        
        layout.addLayout(form_layout)
        
        # 使用BaseDialog的按钮布局
        button_layout = self.create_button_layout(self.validate_and_accept)
        layout.addLayout(button_layout)

    def query_products(self, keyword):
        """查询可选商品"""
        # 获取未关联该供应商的商品
        self.current_price_label.setText("")
        products = api.get_products(keyword)["items"]
        filter_products = [quote['product']['id'] for quote in self.parent().quotes]
        return [product for product in products if product['id'] not in filter_products]
    
    def update_current_price(self):
        """更新当前售价"""
        product = self.product_input.get_selected_item()
        if product:
            self.current_price_label.setText(f"{product['price']}")
        else:
            self.current_price_label.setText("")

    def validate_and_accept(self):
        """验证并保存数据"""
        product = self.product_input.get_selected_item()
        if not product:
            MessageOverlay.warning(self, "请选择商品")
            return
        
        price = self.price_input.value()
        if price <= 0:
            MessageOverlay.warning(self, "请输入有效的报价")
            return
        if price > product['price'] and MessageOverlay.question(self, f"报价高于当前售价\n确定要提交报价 {price} 吗？") == MessageOverlay.REJECTED:
            return
        self.accept()

    @property
    def submit_quote(self):
        product = self.product_input.get_selected_item()
        return {'id': product['id'], 'cost_price': self.price_input.value(), 'product': product}
